package com.cssy.yd.basic.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.entity.BasicBomDO;
import com.cssy.yd.basic.entity.BasicBomRalDO;
import com.cssy.yd.basic.service.IbasicBomRalService;
import com.cssy.yd.basic.service.IbasicBomService;
import com.cssy.yd.logic.entity.LogicPoWareDO;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Controller
@RequestMapping("yd/basic/bom")
public class BasicBomController extends BaseController<BasicBomDO>{

	private static final String itemtype="BOM组";
	private static final String MANAGER = "/yd/basic/bom/BomManager";//列表页面
	private static final String EIDT = "/yd/basic/bom/BomRalOperation";//添加、修改、显示页面
	
	@Resource(name="basicBomService")
	private IbasicBomService basicBomService;
	
	@Resource(name="basicBomRalService")
	private IbasicBomRalService basicBomRalService;
	
	@Resource(name="syCodeService")
	private SyCodeService syCodeService;
	
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}
	
	
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
//		scs.setRemovedProperty("removed");//判断是否有删除标识
		String ID =request.getParameter("ID");
		if(ID!=null&&!"".equals(ID)){
			scs.addCondition("parentid", ID);
		}
		hander.getWheres(scs);	
		SearchResult result=	basicBomService.findListByExample(scs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
		
	}

	@Override
	public String operationForm(HttpServletRequest request,@PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		BasicBomDO bbd=	basicBomService.findListById(id);
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			model.addAttribute("bname", bbd.getTurnoffName());
			model.addAttribute("bid", bbd.getId());
			model.addAttribute("flag", "add");
			model.addAttribute("xx", 1);
		}else{
			SearchConditions scs = new SearchConditions();
			scs.setRemovedProperty(null);//判断是否有删除标识
			scs.addCondition("sunid", bbd.getId(), SearchCondition.OP_EQUAL);
			List<BasicBomRalDO> bomRal=basicBomRalService.findListByExample(scs).getResults();
			if(bbd.getBillstatus()==0){
				model.addAttribute("xx",1);
			}else {
				model.addAttribute("xx", 2);//标示能不能修改内容
			}
			model.addAttribute("bomRal", bomRal);
			model.addAttribute("bbd", bbd);
			model.addAttribute("bname", bbd.getTurnoffName());
			model.addAttribute("bid", bbd.getId());
			model.addAttribute("flag", "edit");
		}
		return EIDT;
	}
	
	
	
	@Override
	public Map<String, Object> save(HttpServletRequest request,
			BasicBomDO curAP, BindingResult result, Model model)
	{
		BodyMsg bodyMap=BodyMsg.getInstance();
		String itemdata =request.getParameter("itemdata");
		if(itemdata==null&&"".equals(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("采购订单内容不能为空！");
			return bodyMap.modelMap;
		}
		try {
			if(curAP.getTurnoffName().equals(itemtype)||curAP.getTurnoffName().equals(request.getParameter("parent"))){
				bodyMap.isFail();
				bodyMap.configWebInfor("不能增加与主类型相同的名称");
			}else{
					basicBomService.bomSave(request, curAP);
					bodyMap.isSuccess();
					bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
					bodyMap.configWebId(curAP.getId());
					}
			
		} catch (Exception e) {			
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()+e.getMessage());
		}
		return bodyMap.modelMap;
		
	}
		

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap=BodyMsg.getInstance();
		try{
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			
			for(String field : fields){
				basicBomService.delete(field, SessionUtil.getUser(request));
			}
		
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed()+e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		String tr=null;
		List<BasicBomDO> list =basicBomService.findAll(itemtype);
		if(list.size()>0){
			tr=tree(list);
		}else{
			String id=IDCodeTypeUtil.getId();
			StringBuffer sf =new StringBuffer();
			sf.append("[");
			for(int i=0;i<list.size();i++){
				sf.append("{");
				sf.append("\"text\":").append("\"").append(itemtype).append("\"").append(",").append("\"id\":").append("\"").append(id).append("\"");
				sf.append("}");
			}
			sf.append("]");
			tr=sf.toString();
			BasicBomDO itemype =new BasicBomDO();
			itemype.setTurnoffCode(syCodeService.getCode("BOM","BOM",SyCode.DATE_YYMM,5));
			itemype.setTurnoffName(itemtype);
			itemype.setId(id);
			basicBomService.save(itemype, SessionUtil.getUser(request));
			
		}
		AjaxUtil.printJSonArr(response, tr);
	}
	
    /**
     * 自调函数 生成tree数据
     **/
	private String  tree(List<BasicBomDO> list) throws SyBaseException {
		List<BasicBomDO> list1 =null;
		StringBuffer sf =new StringBuffer();
		sf.append("[");
		for(int i=0;i<list.size();i++){
			sf.append("{");
			sf.append("\"text\":").append("\"").append(list.get(i).getTurnoffName()).append("\"").append(",").append("\"id\":").append("\"").append(list.get(i).getId()).append("\"");
			list1 =basicBomService.findAllPa(list.get(i).getId());
			if(list1.size()>0){
				sf.append(",").append("\"children\":");
				sf.append(tree(list1));
			}
			if(i==(list.size()-1)){
				sf.append("}");
			}else{
				sf.append("},");
			}
		}
		sf.append("]");
		return sf.toString();
	}
	
	@RequestMapping(value = "/updateState")
	public void updateState(HttpServletRequest request,HttpServletResponse response)throws Exception{
		String id = request.getParameter("rows");
		String checktype = request.getParameter("checktype");
		Map<String,String> map =new HashMap<String, String>();
		try{
			BasicBomDO bbd = basicBomService.findListById(id);
			bbd.setBillstatus(0);
		basicBomService.update(bbd,  SessionUtil.getUser(request));
		map.put("msg", "SUCCESS");
		}catch(Exception e){
			e.printStackTrace();
			map.put("msg", "ERROR");
		}
		AjaxUtil.printJSonArr(response, JSONObject.fromObject(map).toString());
	}
}
